package com.molichuxing.services.infrastructure.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.molichuxing.framework.utils.StringUtil;
import com.molichuxing.services.infrastructure.dto.request.create.IpDetail;
import com.molichuxing.services.infrastructure.service.IpService;
import org.omg.CORBA.TRANSACTION_MODE;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @Author: liuruifeng
 * @Description:
 * @Modified By:
 **/
@Service("ipService")
public class IpServiceImpl implements IpService {
    private static final Logger logger = LoggerFactory.getLogger(IpServiceImpl.class);

    public static void main(String[] args) {
        IpServiceImpl ip = new IpServiceImpl();
        ip.getIpDetail("121.69.60.86");
    }
    @Override
    public IpDetail getIpDetail(String ip) {
        IpDetail result = null;
        if (StringUtil.isEmpty(ip))
            return result;
        try{
            String str = getJsonContent("http://ip.taobao.com/service/getIpInfo.php?ip="+ip);
            logger.error("根据ip获取地址接口，第三方返回值 str ::{}", str);
            if (StringUtil.isEmpty(str))
                return result;

            JSONObject dataJson = JSONObject.parseObject(str);
            if (dataJson == null || StringUtil.isEmpty(dataJson.getString("data"))) {
                logger.error("根据ip获取地址接口，dataJson为null或JdataJson中data值为null dataJson ::{}", dataJson != null ? dataJson.toString(): dataJson);
                return result;
            }
            result = JSON.toJavaObject(dataJson.getJSONObject("data"), IpDetail.class);
            return result;
        }catch(Exception e){
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    public static String getJsonContent(String urlStr) {
        try
        {// 获取HttpURLConnection连接对象
            URL url = new URL(urlStr);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            // 设置连接属性
            httpConn.setConnectTimeout(3000);
            httpConn.setDoInput(true);
            httpConn.setRequestMethod("GET");
            // 获取相应码
            int respCode = httpConn.getResponseCode();
            if (respCode == 200)
            {
                return ConvertStream2Json(httpConn.getInputStream());
            }
        }
        catch (MalformedURLException e)
        {
            logger.error(e.getMessage(), e);
        }
        catch (IOException e)
        {
            logger.error(e.getMessage(), e);
        }
        return "";
    }

    private static String ConvertStream2Json(InputStream inputStream) {
        String jsonStr = "";
        // ByteArrayOutputStream相当于内存输出流
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        // 将输入流转移到内存输出流中
        try
        {
            while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
            {
                out.write(buffer, 0, len);
            }
            // 将内存流转换为字符串
            jsonStr = new String(out.toByteArray());
        }
        catch (IOException e)
        {
            logger.error(e.getMessage(), e);
        }
        return jsonStr;
    }
}
